// 引入axios
import axios from "axios";
import store from "@/store";
import { ElMessage } from "element-plus";

// 创建axios实例
let baseURLs = process.env.VUE_APP_BASE_API;
const httpService = axios.create({
  baseURL: baseURLs,
  // 请求超时时间
  timeout: 60000, //  请求超时时间
});

//添加请求和响应拦截器
const showMessage = (msg) => {
  ElMessage({
    message: msg || "请求异常sss",
    type: "error",
    duration: 3 * 1000,
  });
};
const logout = async () => {
  let result = await get("/logout");

  if (result.data.code === 200) {
    store.commit("RESET_TABS");
    store.dispatch("logout");
    location.reload(); // 为了重新实例化vue-router对象 避免bug
  }
};

// request拦截器
httpService.interceptors.request.use(
  (config) => {
    let token = store.getters.GET_TOKEN;
    if (token) {
      config.headers.token = token;
    }
    return config;
  },
  (error) => {
    // Do something with request error
    showMessage(error);
    return Promise.reject(error);
  }
);

// 添加响应拦截器
httpService.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code === undefined) {
      return Promise.reject("error");
    }
    if (res.code !== 200) {
      if (res.code == 401) {
        // 401:身份信息已过期,需要清空本地持久化的用户信息相关数据，重新登录
        showMessage(res.msg || "登录信息过期，请重新登录");
        setTimeout(() => {
          logout();
        }, 1000);
      }
    }
    return response;
  },
  (error) => {
    // 对响应错误做点什么
    console.log(error.response.data.code);

    if (error.response.data.code == 401) {
      // 401:身份信息已过期,需要清空本地持久化的用户信息相关数据，重新登录
      showMessage("登录信息过期，请重新登录");
      setTimeout(() => {
        logout();
      }, 800);
    } else {
      showMessage(error.message);
    }

    return Promise.reject(error);
  }
);

/*网络请求部分*/

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
const get = (url, params) => {
  return httpService({
    method: "get",
    url: url,
    params: params,
  });
};

/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export const post = (url, params) => {
  return httpService({
    method: "post",
    url: url,
    data: params,
  });
};
/*
 *  文件上传
 *  url:请求地址
 *  params:参数
 * */
export const fileUpload = (url, params = {}) => {
  return httpService({
    url: url,
    method: "post",
    data: params,
    headers: { "Content-Type": "multipart/form-data" },
  });
};

/*
 *  删除请求
 *  url:请求地址
 *  params:参数
 * */
export const deleteReq = (url, data) => {
  return httpService({
    method: "delete",
    url: url,
    params: data,
  });
};

/*
 *  put请求
 *  url:请求地址
 *  params:参数
 * */
export const putReq = (url, data) => {
  return httpService({
    method: "put",
    url: url,
    data: data,
  });
};

/**
 *
 * 返回图片预览地址
 */
export const getServerUrl = () => {
  return baseURLs;
  // return "";
};

export default {
  get,
  post,
  fileUpload,
  getServerUrl,
  deleteReq,
};
